const { diaryApi } = require('../../utils/api');
const { BASE_URL } = require('../../utils/api');

Page({
  data: {
    travelRecords: [],
    showAddButton: true,
    showEditor: false,
    currentDiary: {
      title: '',
      content: '',
      location: '',
      images: [],
      weather: '',
      mood: '',
      date: ''
    },
    loading: false
  },

  onLoad: function() {
    this.loadTravelRecords();
  },

  onShow: function() {
    this.loadTravelRecords();
  },

  // 加载旅行记录
  async loadTravelRecords() {
    try {
      this.setData({ loading: true });
      const response = await diaryApi.getDiaryList();
      console.log('=== 后端返回的原始数据 ===');
      console.log('完整响应:', response);
      
      // 检查响应格式
      if (!response || !response.data || !Array.isArray(response.data)) {
        console.error('响应数据格式错误:', response);
        throw new Error('服务器返回数据格式错误');
      }

      // 处理日记数据
      const travelRecords = response.data.map(diary => {
        console.log('处理日记数据:', diary);
        
        // 处理图片数组
        let images = [];
        if (diary.images) {
          try {
            if (Array.isArray(diary.images)) {
              images = diary.images;
            } else if (typeof diary.images === 'string') {
              // 检查是否是JSON字符串
              if (diary.images.startsWith('[') || diary.images.startsWith('{')) {
                images = JSON.parse(diary.images);
              } else {
                // 如果不是JSON字符串，可能是单个图片URL
                images = [diary.images];
              }
            }
          } catch (e) {
            console.error('解析图片数据失败:', e);
            // 如果解析失败，尝试将整个字符串作为单个图片URL
            images = [diary.images];
          }
        }

        // 处理日期
        const date = diary.date || 
                    (diary.created_at ? diary.created_at.split('T')[0] : null) || 
                    new Date().toISOString().split('T')[0];

        return {
          ...diary,
          images,
          date
        };
      });

      console.log('处理后的日记数据:', travelRecords);

      this.setData({
        travelRecords,
        loading: false
      });
    } catch (error) {
      console.error('加载旅行记录失败:', error);
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  // 显示日记编辑器
  showDiaryEditor: function() {
    const now = new Date();
    const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
    
    this.setData({
      showEditor: true,
      showAddButton: false,
      currentDiary: {
        title: '',
        content: '',
        location: '',
        images: [],
        weather: '',
        mood: '',
        date: dateStr
      }
    });
  },

  // 取消编辑
  cancelEdit: function() {
    this.setData({
      showEditor: false,
      showAddButton: true
    });
  },

  // 处理标题输入
  onTitleInput: function(e) {
    this.setData({
      'currentDiary.title': e.detail.value
    });
  },

  // 处理内容输入
  onContentInput: function(e) {
    this.setData({
      'currentDiary.content': e.detail.value
    });
  },

  // 处理地点输入
  onLocationInput: function(e) {
    this.setData({
      'currentDiary.location': e.detail.value
    });
  },

  // 选择天气
  onWeatherSelect: function(e) {
    this.setData({
      'currentDiary.weather': e.detail.value
    });
  },

  // 选择心情
  onMoodSelect: function(e) {
    this.setData({
      'currentDiary.mood': e.detail.value
    });
  },

  // 选择图片
  async chooseImages() {
    try {
      const res = await wx.chooseImage({
        count: 9 - this.data.currentDiary.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      });

      // 显示上传中提示
      wx.showLoading({
        title: '上传中...',
        mask: true
      });

      // 上传图片
      const uploadPromises = res.tempFilePaths.map(filePath => diaryApi.uploadImage(filePath));
      const uploadedUrls = await Promise.all(uploadPromises);

      this.setData({
        'currentDiary.images': [...this.data.currentDiary.images, ...uploadedUrls]
      });

      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '上传失败',
        icon: 'none'
      });
    }
  },

  // 删除图片
  deleteImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.currentDiary.images;
    images.splice(index, 1);
    this.setData({
      'currentDiary.images': images
    });
  },

  // 预览图片
  previewImage: function(e) {
    const current = e.currentTarget.dataset.src;
    wx.previewImage({
      current: current,
      urls: this.data.currentDiary.images
    });
  },

  // 保存日记
  async saveDiary() {
    const diary = this.data.currentDiary;
    
    // 验证必填字段
    if (!diary.title.trim()) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      });
      return;
    }

    if (!diary.content.trim()) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      });
      return;
    }

    try {
      wx.showLoading({
        title: '保存中...',
        mask: true
      });

      // 创建日记
      await diaryApi.createDiary(diary);

      // 重新加载日记列表
      await this.loadTravelRecords();

      this.setData({
        showEditor: false,
        showAddButton: true
      });

      wx.hideLoading();
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none'
      });
    }
  },

  // 查看日记详情
  viewDiaryDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    console.log('Navigating to diary detail with ID:', id);
    if (!id) {
      wx.showToast({
        title: '日记ID不存在',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: `/pages/diary-detail/diary-detail?id=${id}`,
      success: () => {
        console.log('导航到日记详情页面成功');
      },
      fail: (error) => {
        console.error('导航到日记详情页面失败:', error);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  // 删除日记
  async deleteDiary(e) {
    const id = e.currentTarget.dataset.id;
    try {
      const res = await wx.showModal({
        title: '确认删除',
        content: '确定要删除这篇日记吗？'
      });

      if (res.confirm) {
        wx.showLoading({
          title: '删除中...',
          mask: true
        });

        await diaryApi.deleteDiary(id);
        await this.loadTravelRecords();

        wx.hideLoading();
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '删除失败',
        icon: 'none'
      });
    }
  },

  // 创建日记
  async createDiary() {
    try {
      const { title, content, location, weather, mood, date, images } = this.data;
      
      // 获取用户信息
      const userInfo = wx.getStorageSync('userInfo');
      if (!userInfo || !userInfo.username || !userInfo.password) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }

      // 准备表单数据
      const formData = new FormData();
      formData.append('title', title);
      formData.append('content', content);
      formData.append('location', location);
      formData.append('weather', weather);
      formData.append('mood', mood);
      formData.append('date', date);
      formData.append('username', userInfo.username);
      formData.append('password', userInfo.password);

      // 添加图片
      if (images && images.length > 0) {
        images.forEach((image, index) => {
          formData.append('images', image);
        });
      }

      const response = await diaryApi.createDiary(formData);
      
      if (response.success) {
        wx.showToast({
          title: '创建成功',
          icon: 'success'
        });
        this.setData({
          showForm: false,
          title: '',
          content: '',
          location: '',
          weather: '',
          mood: '',
          date: '',
          images: []
        });
        this.loadTravelRecords();
      } else {
        throw new Error(response.error || '创建失败');
      }
    } catch (error) {
      console.error('创建日记失败:', error);
      wx.showToast({
        title: error.message || '创建失败',
        icon: 'none'
      });
    }
  }
}); 